<template>
    <div class="mobile-requirement-detail">
        <div class="header">
            <h2 class="title">需求详情</h2>
        </div>

        <div class="content-container">
            <!-- 状态标签和操作按钮 -->
            <div class="status-bar">
                <el-tag :color="getStatusColor(requirementData.requirementFatherStatus)">
                    {{ getStatusText(requirementData.requirementFatherStatus) }}
                </el-tag>
                <el-tag class="quick-create" v-if="requirementData.isGetTest < 3"
                    :color="getTestTagColor(requirementData.isGetTest)">
                    {{ getTestTagText(requirementData.isGetTest) }}
                </el-tag>
            </div>

            <!-- 需求标题 -->
            <div class="requirement-title">
                {{ requirementData.requirementName }}
            </div>

            <!-- 需求类型 -->
            <div class="requirement-type">
                <el-icon :color="getTaskTypeColor(requirementData.taskType)">
                    <Flag />
                </el-icon>
                {{ getTaskTypeText(requirementData.taskType) }}
            </div>

            <!-- 人员信息 -->
            <div class="person-info-grid">
                <div class="info-item">
                    <div class="label">创建人</div>
                    <div class="value">{{ requirementData.requirementCreateName || '无' }}</div>
                </div>
                <div class="info-item" v-if="requirementData.requirementAuditName">
                    <div class="label">审核人</div>
                    <div class="value">{{ requirementData.requirementAuditName }}</div>
                </div>
                <div class="info-item" v-if="requirementData.requirementBossName">
                    <div class="label">技术负责人</div>
                    <div class="value">{{ requirementData.requirementBossName }}</div>
                </div>
                <div class="info-item" v-if="requirementData.contactTestBossName">
                    <div class="label">测试负责人</div>
                    <div class="value">{{ requirementData.contactTestBossName }}</div>
                </div>
            </div>

            <!-- 参与人员 -->
            <div class="participants">
                <div class="participant-group">
                    <span class="label">研发人员：</span>
                    <span class="value">{{ requirementData.requirementRelevances ?
                        formatNames(requirementData.requirementRelevances) : '未分配' }}</span>
                </div>
                <div class="participant-group">
                    <span class="label">运维人员：</span>
                    <span class="value">{{ requirementData.requirementLinuxs ?
                        formatNames(requirementData.requirementLinuxs) : '未分配' }}</span>
                </div>
                <div class="participant-group">
                    <span class="label">测试人员：</span>
                    <span class="value">{{ requirementData.contactTestNames ?
                        formatNames(requirementData.contactTestNames) : '未分配' }}</span>
                </div>
            </div>

            <!-- 时间信息 -->
            <div class="time-info">
                <div class="time-item">
                    <div class="label">创建时间</div>
                    <div class="value">{{ formatTime(requirementData.createAt) }}</div>
                </div>
                <div class="time-item">
                    <div class="label">预计结束时间</div>
                    <div class="value">{{ formatTime(requirementData.onlineTime) }}</div>
                </div>
                <div class="time-item" v-if="requirementData.endTime">
                    <div class="label">结束时间</div>
                    <div class="value">{{ formatTime(requirementData.endTime) }}</div>
                </div>
            </div>

            <!-- 需求简述 -->
            <div class="requirement-description">
                <div class="description-header">
                    <el-icon>
                        <Document />
                    </el-icon>
                    <span>需求简述</span>
                    <el-button v-if="canEditDescription" type="primary" size="small"
                        @click="handleOpenEditor">修改</el-button>
                </div>
                <div class="description-content" v-html="requirementData.requirementContent"></div>
            </div>

            <!-- 需求草稿 -->
            <div class="file-section" v-if="draftFiles.length > 0">
                <div class="file-header">
                    <el-icon>
                        <Link />
                    </el-icon>
                    <span>需求草稿</span>
                </div>
                <div class="file-list">
                    <div class="file-item" v-for="(file, index) in draftFiles" :key="index">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span class="file-name">{{ getDisplayFileName(file.fileName || file.name) }}</span>
                        <el-icon class="file-action" @click="previewFile(file.url)">
                            <View />
                        </el-icon>
                        <el-icon class="file-action" @click="downloadFile(file.url)">
                            <Download />
                        </el-icon>
                    </div>
                </div>
            </div>

            <!-- 概要设计部分 -->
            <div class="file-section" v-if="summaryFiles.length > 0">
                <div class="file-header">
                    <el-icon>
                        <Link />
                    </el-icon>
                    <span>概要设计</span>
                    <el-button v-if="canEditSummary" type="primary" size="small"
                        @click="editFiles(2, summaryFiles)">修改</el-button>
                </div>
                <div class="file-list">
                    <div class="file-item" v-for="(file, index) in summaryFiles" :key="index">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span class="file-name">{{ getDisplayFileName(file.fileName || file.name) }}</span>
                        <el-icon class="file-action" @click="previewFile(file.url)">
                            <View />
                        </el-icon>
                        <el-icon class="file-action" @click="downloadFile(file.url)">
                            <Download />
                        </el-icon>
                    </div>
                </div>
            </div>

            <!-- 任务列表部分 -->
            <div class="task-list" v-if="requirementData.itemRequirementChilds?.length > 0">
                <div class="task-header">
                    <span>已分配任务</span>
                    <div class="task-actions">
                        <el-button v-if="canAddTask" type="primary" size="small" plain
                            @click="showAddTaskDialog">新增任务</el-button>
                    </div>
                </div>

                <el-table :data="requirementData.itemRequirementChilds" style="width: 100%">
                    <el-table-column prop="userName" label="归属人" width="90" />
                    <el-table-column label="角色" width="80">
                        <template #default="{ row }">
                            {{ getRoleText(row.isTs) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="processJob" label="任务内容" show-overflow-tooltip />
                    <el-table-column label="预计完成时间" width="120">
                        <template #default="{ row }">
                            {{ formatTime(row.guessTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="guessProcess" label="耗时评估(h)" width="100" />
                    <el-table-column prop="processJobNum" label="难度评分" width="90" />
                    <el-table-column label="任务进度" width="100">
                        <template #default="{ row }">
                            <span :style="{ color: getTaskStatusColor(row) }">{{ getTaskStatusText(row) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否超时" width="100">
                        <template #default="{ row }">
                            <el-button :type="getTimeoutButtonType(row)" size="small" @click="handleTimeout(row)">
                                {{ getTimeoutButtonText(row) }}
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="right" class-name="action-column">
                        <template #default="{ row }">
                            <div class="action-buttons">
                                <el-button v-if="canEditTask(row)" type="primary" size="small" class="action-button"
                                    @click="showEditTaskDialog(row)">修改</el-button>
                                <el-button v-if="canDeleteTask(row)" type="danger" size="small" class="action-button"
                                    @click="confirmDeleteTask(row)">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 移动端新增/修改任务弹窗 -->
            <el-dialog v-model="taskDialogVisible" :title="isEditingTask ? '修改任务' : '新增任务'" width="90%" class="mobile-dialog">
                <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" 
                    label-position="top" class="task-form-mobile">
                    <el-form-item label="角色" prop="role" v-if="!isEditingTask">
                        <el-select v-model="taskForm.role" placeholder="请选择角色" class="mobile-select" @change="updateAvailableUsers">
                            <el-option v-for="role in roleOptions" :key="role.value" :label="role.label" :value="role.value" />
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item label="执行人员" prop="userUUID" v-if="!isEditingTask">
                        <el-select v-model="taskForm.userUUID" placeholder="请选择执行人员" filterable 
                            class="mobile-select" @change="handleUserChange">
                            <el-option v-for="user in availableUsers" :key="user.userUUID" :label="user.userName"
                                :value="user.userUUID" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="归属人" prop="userUUID" v-if="isEditingTask">
                        <el-input v-model="currentTask.userName" disabled class="mobile-input" />
                    </el-form-item>

                    <el-form-item label="任务内容" prop="processJob">
                        <el-input v-model="taskForm.processJob" type="textarea" :rows="2" class="mobile-textarea" />
                    </el-form-item>

                    <el-form-item label="预计完成时间" prop="guessTime">
                        <el-date-picker 
                            v-model="taskForm.guessTime" 
                            type="date" 
                            value-format="YYYY-MM-DD"
                            class="mobile-date-picker"
                            :shortcuts="[
                                { text: '明天', value: getTomorrow() },
                                { text: '3天后', value: getDaysLater(3) },
                                { text: '1周后', value: getDaysLater(7) }
                            ]" />
                    </el-form-item>

                    <div class="mobile-form-row">
                        <el-form-item label="耗时(h)" prop="guessProcess" class="mobile-number-input">
                            <el-input-number v-model="taskForm.guessProcess" :min="1" :max="1000" controls-position="right" />
                        </el-form-item>
                        
                        <el-form-item label="难度" prop="processJobNum" class="mobile-number-input">
                            <el-input-number v-model="taskForm.processJobNum" :min="1" :max="500" controls-position="right" />
                        </el-form-item>
                    </div>
                </el-form>

                <template #footer>
                    <div class="mobile-dialog-footer">
                        <el-button @click="taskDialogVisible = false" class="mobile-cancel-btn">取消</el-button>
                        <el-button type="primary" @click="submitTaskForm" class="mobile-confirm-btn">确定</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 超时原因弹窗 -->
            <el-dialog v-model="timeoutDialogVisible" :title="timeoutForm.isOutTimeMsg ? '查看超时原因' : '填写超时原因'"
                width="90%" class="timeout-dialog">
                <el-form v-if="timeoutForm.isOutTimeMsg">
                    <el-form-item label="超时原因">
                        <el-input v-model="timeoutForm.isOutTimeMsg" type="textarea" :rows="4" readonly
                            class="timeout-textarea" />
                    </el-form-item>
                </el-form>

                <el-form v-else :model="timeoutForm" :rules="timeoutRules" ref="timeoutFormRef">
                    <el-form-item label="超时原因" prop="isOutTimeMsg">
                        <el-input v-model="timeoutForm.isOutTimeMsg" type="textarea" :rows="4"
                            placeholder="请详细说明任务超时的原因" class="timeout-textarea" />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="timeoutDialogVisible = false" class="footer-button">取消</el-button>
                        <el-button v-if="!timeoutForm.isOutTimeMsg" type="primary" @click="submitTimeoutReason"
                            class="footer-button">提交</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 留言和历史记录 -->
            <div class="message-history">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="历史留言" name="messages">
                        <div v-if="commentsData.length === 0" class="empty-message">暂无留言</div>
                        <el-timeline v-else>
                            <el-timeline-item v-for="(item, index) in commentsData" :key="index"
                                :timestamp="formatMessageTime(item.createAt)">
                                <div v-html="`${item.saidUserName}&nbsp;&nbsp;${item.saidContent}`"></div>
                            </el-timeline-item>
                        </el-timeline>
                    </el-tab-pane>
                    <el-tab-pane label="变更历史" name="history">
                        <div v-if="commentsHistorysData.length === 0" class="empty-message">暂无记录</div>
                        <el-timeline v-else>
                            <el-timeline-item v-for="(item, index) in commentsHistorysData" :key="index"
                                :timestamp="formatMessageTime(item.createAt)">
                                <div v-html="`${item.operationUserName}&nbsp;&nbsp;${item.operationHistory}`"></div>
                            </el-timeline-item>
                        </el-timeline>
                    </el-tab-pane>
                </el-tabs>
            </div>

            <!-- 留言输入框 -->
            <div class="comment-input-area" v-if="isComment">
                <el-input v-model="newComment" placeholder="请输入留言..." clearable />
                <el-button type="primary" @click="submitComment">留言</el-button>
            </div>
        </div>

        <!-- 修改需求详情弹窗 -->
        <el-dialog v-model="showEditorDialog" title="修改需求详情" width="90%">
            <el-input type="textarea" :rows="10" v-model="editedContent"></el-input>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showEditorDialog = false" class="footer-button">取消</el-button>
                    <el-button type="primary" @click="saveEditedContent" class="footer-button">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { Flag, Document, Link, View, Download } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import useUserStore from '@/store/modules/user';
import {
    PostRequirement, GetSaidContentList, GetOperationHistorys,
    PostAddSaidContents, PostUpdateRequirementMsg, postAddAvgRequirement,
    PutUpdateChildMsg,
    PostOutTimeRequirementMsg,
    PostAvgDeleteRequirement,
    GetGetOnlineTaskGuarantors
} from '@/api/newDemands/index';
const route = useRoute();
const userStore = useUserStore();
const userName = ref('');

// 数据状态
const requirementData = ref<any>({});
const draftFiles = ref<any[]>([]);
const summaryFiles = ref<any[]>([]);
const commentsData = ref<any[]>([]);
const commentsHistorysData = ref<any[]>([]);
const loading = ref(false);
const activeTab = ref('messages');
const newComment = ref('');
const showEditorDialog = ref(false);
const editedContent = ref('');
const availableUsers = ref<any[]>([]);

// 任务相关状态
const taskDialogVisible = ref(false);
const isEditingTask = ref(false);
const currentTask = ref<any>(null);
const taskFormRef = ref();
const taskForm = reactive({
    userUUID: '',
    userName: '',
    role: '1', // 默认研发角色
    processJob: '',
    guessTime: '',
    guessProcess: 1,
    processJobNum: 1
});

// 移动端优化 - 自动填充当前日期
const fillDefaultDate = () => {
    if (!taskForm.guessTime) {
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        taskForm.guessTime = tomorrow.toISOString().split('T')[0];
    }
};

const taskRules = {
    role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    userUUID: [{ required: true, message: '请选择执行人员', trigger: 'blur' }],
    processJob: [{ required: true, message: '请输入任务内容', trigger: 'blur' }],
    guessTime: [{ required: true, message: '请选择预计完成时间', trigger: 'blur' }],
    guessProcess: [{ required: true, message: '请输入耗时评估', trigger: 'blur' }],
    processJobNum: [{ required: true, message: '请输入难度评分', trigger: 'blur' }]
};

// 超时相关状态
const timeoutDialogVisible = ref(false);
const timeoutFormRef = ref();
const timeoutForm = reactive({
    requirementChildId: '',
    isOutTimeMsg: ''
});

const timeoutRules = {
    isOutTimeMsg: [{ required: true, message: '请输入超时原因', trigger: 'blur' }]
};

// 计算属性
const canEditDescription = computed(() => {
    const userAuthId = localStorage.getItem('authorityId');
    return (
        userAuthId === '888' ||
        userAuthId === '999' ||
        userName.value === requirementData.value.requirementBossName ||
        userName.value === requirementData.value.requirementCreateName
    );
});

const canEditSummary = computed(() => {
    return userName.value === requirementData.value.requirementBossName;
});

const canAddTask = computed(() => {
    const status = requirementData.value.requirementFatherStatus;
    if (requirementData.value.taskType === 1 || requirementData.value.taskType === 3) {
        return (
            (userName.value === requirementData.value.contactTestBossName ||
                userName.value === requirementData.value.requirementBossName) &&
            status <= 7
        );
    } else {
        return (
            (userName.value === requirementData.value.contactTestBossName ||
                userName.value === requirementData.value.requirementBossName) &&
            status === 1
        );
    }
});

const isComment = computed(() => {
    return route.meta.isComment !== false;
});

// 方法
const getRequirementData = async () => {
    loading.value = true;
    try {
        const { data } = await PostRequirement({ id: Number(route.params.id) });
        if (data.code === 200) {
            requirementData.value = data.data;

            // 处理文件数据
            if (data.data.itemRequirementWorldDraft) {
                draftFiles.value = data.data.itemRequirementWorldDraft.split('|').map((url: any) => ({
                    url,
                    fileName: url.split('/').pop(),
                    name: url.split('/').pop()
                }));
            }

            if (data.data.itemRequirementWorldSummary) {
                summaryFiles.value = data.data.itemRequirementWorldSummary.split('|').map((url: any) => ({
                    url,
                    fileName: url.split('/').pop(),
                    name: url.split('/').pop()
                }));
            }

            // 获取可用用户列表
            const { data: usersData } = await GetGetOnlineTaskGuarantors();
            if (usersData.code === 200) {
                availableUsers.value = usersData.data.map((user:any) => ({
                    userUUID: user.uuid,
                    userName: user.userName
                }));
            }

            await getComments();
            await getHistory();
        } else {
            ElMessage.error(data.msg);
        }
    } catch (error) {
        ElMessage.error('获取需求详情失败');
    } finally {
        loading.value = false;
    }
};

// 生成UUID的简单方法（实际项目中应该从API获取）
// 此方法已完全移除

const handleUserChange = (userUUID: string) => {
    const selectedUser = availableUsers.value.find(user => user.userUUID === userUUID);
    if (selectedUser) {
        taskForm.userName = selectedUser.userName;
    }
};

const getComments = async () => {
    try {
        const { data } = await GetSaidContentList(Number(route.params.id));
        if (data.code === 200) {
            commentsData.value = data.data;
        }
    } catch (error) {
        ElMessage.error('获取留言失败');
    }
};

const getHistory = async () => {
    try {
        const { data } = await GetOperationHistorys(Number(route.params.id));
        if (data.code === 200) {
            commentsHistorysData.value = data.data;
        }
    } catch (error) {
        ElMessage.error('获取历史记录失败');
    }
};

const submitComment = async () => {
    if (!newComment.value.trim()) {
        ElMessage.warning('留言内容不能为空');
        return;
    }

    try {
        const { data } = await PostAddSaidContents({
            requirementId: Number(route.params.id),
            saidContent: newComment.value
        });

        if (data.code === 200) {
            ElMessage.success('留言成功');
            newComment.value = '';
            await getComments();
        } else {
            ElMessage.error(data.msg);
        }
    } catch (error) {
        ElMessage.error('留言失败');
    }
};

const handleOpenEditor = () => {
    editedContent.value = requirementData.value.requirementContent;
    showEditorDialog.value = true;
};

const saveEditedContent = async () => {
    try {
        const { data } = await PostUpdateRequirementMsg({
            requirementId: route.params.id,
            requirementContent: editedContent.value
        });

        if (data.code === 200) {
            ElMessage.success('修改成功');
            showEditorDialog.value = false;
            await getRequirementData();
        } else {
            ElMessage.error(data.msg);
        }
    } catch (error) {
        ElMessage.error('修改失败');
    }
};

// 显示新增任务对话框
const showAddTaskDialog = async () => {
    isEditingTask.value = false;
    resetTaskForm();
    fillDefaultDate();
    
    // 初始化角色选项
    taskForm.role = '1'; // 默认研发
    await updateAvailableUsers();
    
    taskDialogVisible.value = true;
};

const roleOptions = [
    { value: '1', label: '研发' },
    { value: '2', label: '运维' },
    { value: '3', label: '测试' }
];

const updateAvailableUsers = async () => {
    // 使用接口获取所有人员
    try {
        const { data } = await GetGetOnlineTaskGuarantors();
        if (data.code === 200) {
            availableUsers.value = data.data.map((user:any) => ({
                userUUID: user.uuid,  // 使用接口返回的uuid
                userName: user.userName
            }));
        }
    } catch (error) {
        console.error('获取人员列表失败:', error);
        availableUsers.value = [];
    }
};

// 显示修改任务对话框
const showEditTaskDialog = (task: any) => {
    isEditingTask.value = true;
    currentTask.value = task;
    Object.assign(taskForm, {
        processJob: task.processJob,
        guessTime: task.guessTime,
        guessProcess: task.guessProcess,
        processJobNum: task.processJobNum
    });
    taskDialogVisible.value = true;
};

// 重置任务表单
const resetTaskForm = () => {
    Object.assign(taskForm, {
        userUUID: '',
        userName: '',
        processJob: '',
        guessTime: '',
        guessProcess: 1,
        processJobNum: 1
    });
};

// 提交任务表单
const submitTaskForm = async () => {
    try {
        await taskFormRef.value.validate();

        const taskItem = {
            userUUID: taskForm.userUUID,
            userName: taskForm.userName,
            processJob: taskForm.processJob,
            guessTime: taskForm.guessTime,
            guessProcess: taskForm.guessProcess,
            processJobNum: taskForm.processJobNum,
            isTs: Number(taskForm.role)
        };

        const taskData = {
            itemRequirementId: requirementData.value.ID,
            devs: taskForm.role === '1' ? [taskItem] : [],
            ms: taskForm.role === '2' ? [taskItem] : [],
            ts: taskForm.role === '3' ? [taskItem] : []
        };

        if (isEditingTask.value) {
            // 修改任务
            const { data } = await PutUpdateChildMsg({
                childId: currentTask.value.ID,
                ...taskForm
            });

            if (data.code === 200) {
                ElMessage.success('任务修改成功');
                await getRequirementData();
            } else {
                ElMessage.error(data.msg);
            }
        } else {
            // 新增任务
            const { data } = await postAddAvgRequirement(taskData);

            if (data.code === 200) {
                ElMessage.success('任务添加成功');
                await getRequirementData();
            } else {
                ElMessage.error(data.msg);
            }
        }

        taskDialogVisible.value = false;
    } catch (error) {
        console.error('提交任务失败:', error);
        ElMessage.error('提交任务失败');
    }
};

// 确认删除任务
const confirmDeleteTask = (task: any) => {
    ElMessageBox.confirm(`确定要删除【${task.userName}】的任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteTask(task);
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 删除任务
const deleteTask = async (task: any) => {
    try {
        const { data } = await PostAvgDeleteRequirement({
            itemRequirementId: requirementData.value.ID,
            devs: task.isTs === 1 ? [{
                userUUID: task.userUUID,
                userName: task.userName
            }] : [],
            ts: task.isTs === 3 ? [{
                userUUID: task.userUUID,
                userName: task.userName
            }] : []
        });

        if (data.code === 200) {
            ElMessage.success('任务删除成功');
            await getRequirementData();
        }
    } catch (error) {
        console.error('删除任务失败:', error);
        ElMessage.error('删除任务失败');
    }
};

// 处理超时
const handleTimeout = (task: any) => {
    Object.assign(timeoutForm, {
        requirementChildId: task.ID,
        isOutTimeMsg: task.isOutTimeMsg || ''
    });

    timeoutDialogVisible.value = true;
};

// 提交超时原因
const submitTimeoutReason = async () => {
    try {
        await timeoutFormRef.value.validate();

        const { data } = await PostOutTimeRequirementMsg({
            requirementChildId: Number(timeoutForm.requirementChildId),
            isOutTimeMsg: timeoutForm.isOutTimeMsg
        });

        if (data.code === 200) {
            ElMessage.success('超时原因提交成功');
            timeoutDialogVisible.value = false;
            await getRequirementData();
        }
    } catch (error) {
        console.error('提交超时原因失败:', error);
    }
};


// 工具方法
const formatNames = (names: string) => {
    if (!names) return '';
    return names.split(',').join('、');
};

const formatTime = (time: string) => {
    if (!time) return '';
    return new Date(time).toLocaleString();
};

const formatMessageTime = (time: string) => {
    return formatTime(time);
};

const getStatusColor = (status: number) => {
    switch (status) {
        case 1: return '#909399'; // 待分配
        case 2: return '#409EFF'; // 开发中
        case 3: return '#E6A23C'; // 待测试
        case 4: return '#67C23A'; // 测试中
        case 5: return '#F56C6C'; // 测试完成
        case 6: return '#909399'; // 待上线
        case 7: return '#409EFF'; // 上线中
        case 8: return '#67C23A'; // 已上线
        case 9: return '#909399'; // 已关闭
        default: return '#909399';
    }
};

const getStatusText = (status: number) => {
    switch (status) {
        case 1: return '待分配';
        case 2: return '开发中';
        case 3: return '待测试';
        case 4: return '测试中';
        case 5: return '测试中';
        case 6: return '待上线';
        case 7: return '上线中';
        case 8: return '已上线';
        case 9: return '已关闭';
        default: return '未知状态';
    }
};

const getTaskTypeColor = (type: number) => {
    switch (type) {
        case 1: return '#409EFF'; // 功能需求
        case 2: return '#67C23A'; // 优化需求
        case 3: return '#E6A23C'; // 缺陷修复
        case 4: return '#F56C6C'; // 紧急修复
        default: return '#909399';
    }
};

const getTaskTypeText = (type: number) => {
    switch (type) {
        case 1: return '功能需求';
        case 2: return '优化需求';
        case 3: return '缺陷修复';
        case 4: return '紧急修复';
        default: return '其他类型';
    }
};

const getTestTagColor = (status: number) => {
    return status === 2 ? '#67C23A' : '#F56C6C';
};

const getTestTagText = (status: number) => {
    return status === 2 ? '测试参与' : '无需测试';
};

const getRoleText = (role: number) => {
    switch (role) {
        case 1: return '研发';
        case 2: return '运维';
        case 3: return '测试';
        default: return '其他';
    }
};

const getTaskStatusColor = (task: any) => {
    if (task.isTs === 3 && task.requirementChildStatus < 5) return '#E6A23C'; // 等待提测
    if (task.requirementChildStatus === 5) {
        switch (task.submitTestNext) {
            case 1: return '#E6A23C'; // 待测试
            case 2: return '#67C23A'; // 测试中
            case 3: return '#F56C6C'; // 测试完成
            default: return '#909399';
        }
    }
    return getStatusColor(task.requirementChildStatus);
};

const getTaskStatusText = (task: any) => {
    if (task.isTs === 3 && task.requirementChildStatus < 5) return '等待提测';
    if (task.requirementChildStatus === 5) {
        switch (task.submitTestNext) {
            case 1: return '待测试';
            case 2: return '测试中';
            case 3: return '测试完成';
            default: return '未知状态';
        }
    }
    return getStatusText(task.requirementChildStatus);
};

const getTimeoutButtonType = (task: any) => {
    if (task.isOutTime === '否' || !task.isOutTime) return 'success';
    return task.isOutTimeMsg ? 'primary' : 'danger';
};

const getTimeoutButtonText = (task: any) => {
    if (task.isOutTime === '否' || !task.isOutTime) return '未超时';
    return task.isOutTimeMsg ? '查看原因' : '填写原因';
};

const canEditTask = (task: any) => {
    if (task.isTs === 2 || task.isTs === 1) {
        return userName.value === task.avgUserName;
    } else if (task.isTs === 3) {
        return userName.value === task.avgUserName;
    }
    return false;
};

const canDeleteTask = (task: any) => {
    if (task.isTs === 2 || task.isTs === 1) {
        return userName.value === task.avgUserName;
    } else if (task.isTs === 3) {
        return userName.value === task.avgUserName;
    }
    return false;
};

const getDisplayFileName = (fileName: string) => {
    if (!fileName) return '';
    const parts = fileName.split('_');
    return parts.length > 1 ? parts[3] : fileName;
};

const previewFile = (url: string) => {
    window.open(url, '_blank');
};

const downloadFile = (url: string) => {
    const link = document.createElement('a');
    link.href = url;
    link.download = url.split('/').pop() || 'download';
    link.click();
};

const editFiles = (type: number, files: any[]) => {
    ElMessage.info(`修改文件类型 ${type}`);
};


// 获取所有人
const allDevsRequirementUsers = ref<any>([]);// 已分配任务人员
const getGetOnlineTaskGuarantors = async () => {
    const { data } = await GetGetOnlineTaskGuarantors();
    if (data.code == 200) {
        allDevsRequirementUsers.value = data.data;
    } else {
        ElMessage.error(data.msg);
    }
}

// 日期处理方法
const getTomorrow = () => {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    return tomorrow.toISOString().split('T')[0];
};

const getDaysLater = (days: number) => {
    const today = new Date();
    const later = new Date(today);
    later.setDate(today.getDate() + days);
    return later.toISOString().split('T')[0];
};

// 生命周期
onMounted(async () => {
    getGetOnlineTaskGuarantors();
    getRequirementData();
    await userStore.getUseInfo();
    userName.value = userStore.userInfo.nickName;
});
</script>

<style lang="scss" scoped>
.mobile-requirement-detail {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    font-size: 14px;
    line-height: 1.5;
    color: #333;

    .header {
        position: sticky;
        top: 0;
        z-index: 100;
        background-color: #409eff;
        color: white;
        padding: 12px 16px;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        .title {
            margin: 0;
            font-size: 18px;
            font-weight: 500;
            flex: 1;
            text-align: center;
            padding-right: 40px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    .content-container {
        padding: 16px;
        background-color: white;
        margin: 8px;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .status-bar {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            gap: 8px;
            flex-wrap: wrap;

            .el-tag {
                color: white;
                margin: 2px;
            }

            .quick-create {
                margin-left: auto;
            }
        }

        .requirement-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
            word-break: break-word;
        }

        .requirement-type {
            display: flex;
            align-items: center;
            gap: 4px;
            margin-bottom: 16px;
            color: #666;
            font-size: 14px;
        }

        .person-info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
            margin-bottom: 16px;

            .info-item {
                display: flex;
                flex-direction: column;
                padding: 8px;
                background: #f8fafc;
                border-radius: 4px;
                border-left: 3px solid #409eff;

                .label {
                    font-size: 12px;
                    color: #909399;
                    margin-bottom: 4px;
                }

                .value {
                    font-size: 14px;
                    color: #333;
                    font-weight: 500;
                    word-break: break-word;
                }
            }
        }

        .participants {
            margin-bottom: 16px;
            padding: 12px;
            background: #f8fafc;
            border-radius: 4px;

            .participant-group {
                margin-bottom: 8px;
                display: flex;

                .label {
                    font-weight: bold;
                    margin-right: 8px;
                    min-width: 80px;
                }

                .value {
                    flex: 1;
                    word-break: break-word;
                }
            }
        }

        .time-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 16px;
            padding: 12px;
            background: #f8fafc;
            border-radius: 4px;
            flex-wrap: wrap;

            .time-item {
                flex: 1;
                min-width: 120px;
                margin-bottom: 8px;
                text-align: left;

                .label {
                    font-size: 12px;
                    color: #909399;
                    margin-bottom: 4px;
                }

                .value {
                    font-size: 14px;
                    color: #333;
                    word-break: break-word;
                }
            }
        }

        .requirement-description {
            margin-bottom: 16px;

            .description-header {
                display: flex;
                align-items: center;
                margin-bottom: 8px;

                .el-icon {
                    margin-right: 8px;
                }

                .el-button {
                    margin-left: auto;
                }
            }

            .description-content {
                padding: 12px;
                background: #f8fafc;
                border-radius: 4px;
                line-height: 1.6;
                word-break: break-word;
            }
        }

        .file-section {
            margin-bottom: 16px;

            .file-header {
                display: flex;
                align-items: center;
                margin-bottom: 8px;

                .el-icon {
                    margin-right: 8px;
                }

                .el-button {
                    margin-left: auto;
                }
            }

            .file-list {
                .file-item {
                    display: flex;
                    align-items: center;
                    padding: 8px 12px;
                    border-bottom: 1px dashed #e4e7ed;

                    .el-icon {
                        margin-right: 8px;
                        color: #409eff;
                    }

                    .file-name {
                        flex: 1;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    .file-action {
                        margin-left: 12px;
                        cursor: pointer;
                        color: #409eff;

                        &:hover {
                            color: #79bbff;
                        }
                    }
                }
            }
        }

        .task-list {
            margin-bottom: 16px;

            .task-header {
                display: flex;
                align-items: center;
                margin-bottom: 12px;
                flex-wrap: wrap;

                span {
                    font-weight: bold;
                    margin-bottom: 8px;
                    width: 100%;
                }

                .task-actions {
                    margin-left: auto;
                    display: flex;
                    gap: 8px;
                    width: 100%;
                    justify-content: flex-end;

                    .el-button {
                        margin: 2px 0;
                    }
                }
            }
        }

        .message-history {
            margin-bottom: 16px;

            .empty-message {
                color: #909399;
                text-align: center;
                padding: 16px;
            }

            .el-timeline {
                padding-left: 16px;

                .el-timeline-item {
                    padding-bottom: 16px;
                }
            }
        }

        .comment-input-area {
            display: flex;
            gap: 8px;
            margin-top: 16px;

            .el-input {
                flex: 1;
            }
        }
    }
}

/* 操作按钮样式优化 */
.action-column {
    .action-buttons {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
        gap: 4px;

        .action-button {
            padding: 5px 8px;
            margin: 0;
            min-width: auto;
            font-size: 12px;
        }
    }
}

/* 弹窗样式优化 */
/* 弹窗样式优化 - 修复后 */
:deep(.el-dialog) {
    max-width: 100%;
    margin: 20px auto;
}

:deep(.el-dialog__body) {
    padding: 15px;
}

:deep(.el-dialog) .el-form-item {
    margin-bottom: 16px;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    padding-top: 15px;

    .footer-button {
        flex: 1;
        max-width: 120px;
        margin: 0 5px;
    }
}

.timeout-textarea {
    width: 100%;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    padding-top: 15px;

    .footer-button {
        flex: 1;
        max-width: 120px;
        margin: 0 5px;
    }
}

.timeout-textarea {
    width: 100%;
}

/* 移动端特定样式 */
@media (max-width: 768px) {
    /* 新增任务按钮样式 */
    .mobile-task-button {
        padding: 12px 16px;
        width: 100%;
        margin: 8px 0;
        font-size: 16px;
        
        .el-icon {
            margin-right: 6px;
            font-size: 18px;
        }
    }

    /* 移动端表单优化 */
    .task-form-mobile {
        .el-form-item {
            margin-bottom: 20px;
            
            .el-form-item__label {
                font-size: 16px;
                padding-bottom: 8px;
                color: #606266;
                font-weight: 500;
            }
        }
        
        .mobile-select, 
        .mobile-input,
        .mobile-date-picker {
            width: 100%;
            
            .el-input__inner {
                height: 48px;
                font-size: 16px;
            }
        }
        
        .mobile-textarea {
            .el-textarea__inner {
                min-height: 100px !important;
                font-size: 16px;
            }
        }
        
        .mobile-number-input {
            flex: 1;
            
            .el-input-number {
                width: 100%;
                
                .el-input__inner {
                    text-align: center;
                    font-size: 16px;
                    height: 48px;
                }
            }
        }
        
        .mobile-form-row {
            display: flex;
            gap: 16px;
            
            .el-form-item {
                flex: 1;
                margin-bottom: 0;
            }
        }
    }
    
    .mobile-dialog-footer {
        display: flex;
        gap: 16px;
        padding-top: 16px;
        
        .mobile-cancel-btn,
        .mobile-confirm-btn {
            flex: 1;
            height: 48px;
            font-size: 16px;
        }
    }

    /* 表格操作按钮调整为垂直排列 */
    .action-column {
        .action-buttons {
            flex-direction: column;
            align-items: flex-end;

            .action-button {
                width: 100%;
                margin: 2px 0;
            }
        }
    }

    /* 弹窗按钮调整为块级元素 */
    .dialog-footer {
        flex-direction: column;
        align-items: center;

        .footer-button {
            max-width: 100%;
            width: 100%;
            margin: 5px 0;
        }
    }

    /* 调整表格其他列的宽度 */
    :deep(.el-table) {
        .el-table__cell {
            padding: 8px 4px;

            &.el-table__expand-column {
                padding: 0;
                width: 30px;
            }
        }
    }

    /* 调整人员信息网格为单列 */
    .person-info-grid {
        grid-template-columns: 1fr !important;
    }
}

@media (max-width: 480px) {

    /* 进一步缩小表格字体和间距 */
    :deep(.el-table) {
        font-size: 12px;

        .el-table__cell {
            padding: 6px 2px;
        }
    }

    /* 调整状态标签和按钮的间距 */
    .status-bar {

        .el-tag,
        .el-button {
            margin: 2px;
        }
    }

    /* 调整任务标题区域 */
    .task-header {
        .task-actions {
            .el-button {
                width: 100%;
                margin: 4px 0;
            }
        }
    }

    /* 调整时间信息为单列 */
    .time-info {
        flex-direction: column;

        .time-item {
            width: 100%;
            text-align: left !important;
        }
    }

    /* 调整弹窗内表单元素间距 */
    :deep(.el-dialog) {
        .el-form-item {
            margin-bottom: 12px;
        }
    }
}
</style>